// 收货地址 
<template>
  <div class="container">
    <h4>收货地址</h4>

    <div class="flexk">
      <p>
        <span>{{defaultAddress}}</span>
      </p>
      <el-button type="text" @click="dialogFormVisible = true">设置</el-button>
    </div>

    <el-dialog title="选择地址" :visible.sync="dialogFormVisible">
      <div class="dialogk">
        <ul class="content-left">
          <li v-for="(item,index) in getAddressData" :key="index">
            <el-radio-group v-model="radio">
              <el-radio
                :label="index"
              >{{item.province_name}}{{item.city_name}}{{item.district_name}}{{item.address}}{{item.consignee}}（收）{{item.phone}}</el-radio>
            </el-radio-group>
            <div>
              <!-- <el-button size="mini" type="warning" @click="edit(item.id,item)">编 辑</el-button> -->
              <el-button size="mini" type="danger" @click="del(item.id)">删 除</el-button>
            </div>
          </li>
        </ul>
      </div>
      <el-button type="text" @click="NewAddress">
        <i>+</i> 新增地址
      </el-button>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddressSelection()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增地址" :visible.sync="dialogFormVisible2">
      <div class="dialogk2">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="收货人" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="ruleForm.tel"></el-input>
          </el-form-item>
          <el-form-item label="所在地区" prop="region">
            <el-select
              @change="region1"
              v-model="ruleForm.region1.id"
              placeholder="请选择省份"
              size="mini"
            >
              <el-option
                v-for="item in ruleForm.region1"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select
              @change="region2"
              v-model="ruleForm.region2.id"
              placeholder="请选择城市"
              size="mini"
            >
              <el-option
                v-for="item in ruleForm.region2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>

            <el-select
              @change="region3"
              v-model="ruleForm.region3.id"
              placeholder="请选择所在区"
              size="mini"
            >
              <el-option
                v-for="item in ruleForm.region3"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="desc">
            <el-input type="textarea" v-model="ruleForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="默 认">
            <el-switch v-model="ruleForm.value"></el-switch>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <!-- <el-button type="primary" @click="dialogFormVisible2 = false">确 定</el-button> -->
        <el-button type="danger" v-if="!conversion" @click="newAddressConfirmation">确 定</el-button>
        <el-button type="primary" v-else @click="editConfirmation">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ReceivingAddress",

  data() {
    return {
      editId: "", // 保存住这个id 以便编辑的确认接口的使用
      conversion: false, //按钮的切换 显示与隐藏触发不同的接口
      defaultAddress: "", // 默认地址 展示
      radio: "1", // 默认地址的位置
      getAddressData: [], // 获取地址存储的数组
      AddressCombination: [], // 地址组合放进这个里面      后期把这个数组给后台就好
      dialogFormVisible: false,
      dialogFormVisible2: false,
      ruleForm: {
        name: "",
        tel: "",
        region1: [],
        region2: [],
        region3: [],
        desc: "",
        value: false // 默认地址的选项
      },
      rules: {
        name: [
          { required: true, message: "请输入收货人姓名", trigger: "blur" }
        ],
        tel: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
        region1: [{ required: true, message: "请选择省份", trigger: "change" }],
        region2: [{ required: true, message: "请选择城市", trigger: "change" }],
        region3: [
          { required: true, message: "请选择所在区", trigger: "change" }
        ],
        desc: [{ required: true, message: "请填写详细地址", trigger: "blur" }]
      }
    }
  },

  methods: {
    // 地址选择的radio
    AddressSelection() {
      this.dialogFormVisible = false
      const oldAddress = this.getAddressData[this.radio]
      console.log(oldAddress)    
      this.defaultAddress = `
        ${oldAddress.province_name} 
        ${oldAddress.city_name}  
        ${oldAddress.district_name} 
        ${oldAddress.address}
        ${oldAddress.consignee}
        ${oldAddress.phone}
      `
      let changesAddress = `
        ${oldAddress.province_name} 
        ${oldAddress.city_name}  
        ${oldAddress.district_name} 
        ${oldAddress.address}
      `
      let changesUser = `
        ${oldAddress.consignee}
        ${oldAddress.phone}
      `

      this.$emit("addressChanges", changesAddress, changesUser, oldAddress.id)
      console.log(this.getAddressData)
      this.$emit("sameReceipt")
      this.$store.commit("changesAddress",oldAddress)   
    
    },
    // 新增地址按钮  弹出
    NewAddress() {
      this.dialogFormVisible2 = true
      this.conversion = false
      // 修复 点击新增时的bug
      this.ruleForm.name = ""
      this.ruleForm.tel = ""
      this.ruleForm.desc = ""
    },

    // 新增地址的确认
    async newAddressConfirmation() {
      // this.conversion = true
      console.log(this.AddressCombination)
      let [
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
        this.$store.state.UserInfor.user_id,
        this.ruleForm.name,
        this.AddressCombination["province"].id,
        this.AddressCombination["province"].name,
        this.AddressCombination["city"].id,
        this.AddressCombination["city"].name,
        this.AddressCombination["area"].id,
        this.AddressCombination["area"].name,
        this.ruleForm.desc,
        this.ruleForm.tel,
        1,
        ""
      ]

      if (this.ruleForm.value) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      let obj = {
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      let arr = Object.values(obj)
      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/saveaddress",
        data: {
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      if (addAddress.data.State.Code == 200) {
        this.dialogFormVisible2 = false
        this.$notify({
          title: "成功",
          message: "成功增加地址...",
          type: "success"
        })
      }
      
      this.getAddress()
    },
    // 获取收货地址
    async getAddress() {
      const user_id = this.$store.state.UserInfor.user_id
      // console.log(user_id)
      let address = await this.$http({
        method: "post",
        url: "/api/home/index/getaddresslist",
        data: {
          user_id,
          type: "1"
        }
      })
      if (address.data.State.Code == 200) {
        let changesAddress = ""
        let changesUser = ""
        this.getAddressData = address.data.data
        this.getAddressData.forEach((element, index) => {
          if (element.is_default == 1) {
            this.defaultAddress = `
              ${element.province_name} 
              ${element.city_name} 
              ${element.district_name} 
              ${element.address}
              ${element.consignee} 
              ${element.phone}
            `
            this.radio = index

            changesAddress = `
              ${element.province_name} 
              ${element.city_name} 
              ${element.district_name} 
              ${element.address}
            `
            changesUser = `
              ${element.consignee} 
              ${element.phone}
            `
          }
        })
        const oldAddress = this.getAddressData[this.radio]  
        if(changesAddress && changesUser && oldAddress.id){
          this.$emit("addressChanges", changesAddress, changesUser, oldAddress.id)
          this.$store.commit("changesAddress",address.data.data[0])
        }       

        
      }
      // console.log(this.getAddressData)
    },
    // 地址删除按钮的操作
    async del(transmitId) {
      let user_id = this.$store.state.UserInfor.user_id
      let id = transmitId
      const delRes = await this.$http({
        method: "post",
        url: "/api/home/index/deladdress",
        data: {
          user_id,
          id
        }
      })
      if (delRes.data.State.Code == 200) {
        this.$notify({
          title: "成功",
          message: "成功刪除该地址...",
          type: "success"
        })
        this.getAddress()
        // 当获取到数据后在进行判断 故用了一个定时器
        setTimeout(()=>{
          if(!this.getAddressData.length){
            this.defaultAddress = ""
          }
        },1000)
        
      }
      console.log(delRes)
      
    },
    // 地址编辑按钮的处理
    edit(transmitId, option) {
      this.conversion = true
      this.dialogFormVisible2 = true
      this.editId = transmitId
      // console.log(option)
      this.ruleForm.name = option.consignee
      this.ruleForm.tel = option.phone
      this.ruleForm.desc = option.address
      this.getAddress()
    },
    // 编辑确认按钮事件
    async editConfirmation() {
      this.conversion = false
      let [
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      ] = [
        this.editId,
        this.$store.state.UserInfor.user_id,
        this.ruleForm.name,
        this.AddressCombination["province"].id,
        this.AddressCombination["province"].name,
        this.AddressCombination["city"].id,
        this.AddressCombination["city"].name,
        this.AddressCombination["area"].id,
        this.AddressCombination["area"].name,
        this.ruleForm.desc,
        this.ruleForm.tel,
        1,
        ""
      ]

      if (this.ruleForm.value) {
        is_default = "1"
      } else {
        is_default = "0"
      }
      console.log(
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default
      ) //默认地址 0：不默认，1：默认
      let obj = {
        id,
        user_id, //用户ID
        consignee, //收货人
        province_id, //省份id
        province_name, //省份名称
        city_id, //城市id
        city_name, //城市名称
        district_id, //地区id
        district_name, //地区名称
        address, //详细地址
        phone, //联系电话
        type, //1：收货地址，2：发票地址
        is_default //默认地址 0：不默认，1：默认
      }
      let arr = Object.values(obj)
      if (arr.includes("")) {
        this.$notify({
          title: "警告",
          message: "请填写完整的地址信息",
          type: "warning"
        })
        return
      }

      let addAddress = await this.$http({
        method: "post",
        url: "/api/home/index/editaddress",
        data: {
          id,
          user_id, //用户ID
          consignee, //收货人
          province_id, //省份id
          province_name, //省份名称
          city_id, //城市id
          city_name, //城市名称
          district_id, //地区id
          district_name, //地区名称
          address, //详细地址
          phone, //联系电话
          type, //1：收货地址，2：发票地址
          is_default //默认地址 0：不默认，1：默认
        }
      })
      console.log(addAddress)
      if (addAddress.data.State.Code == 200) {
        console.log(addAddress)
        this.dialogFormVisible2 = false
        this.$notify({
          title: "成功",
          message: "成功修改地址...",
          type: "success"
        })
      }
      this.getAddress()
    },
    // 通过id匹配名字
    SearchItem(pid, obj) {
      let mySearchItem = obj.find(obj => {
        return obj.id === pid
      })
      return mySearchItem
    },

    async region1() {
      let pid = this.ruleForm.region1.id
      let obj = this.ruleForm.region1
      this.SearchItem(pid, obj)

      this.AddressCombination["province"] = this.SearchItem(pid, obj)
      // console.log(this.AddressCombination)

      // console.log(pid)
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        this.ruleForm.region2 = myProvince.data
      }
    },

    async region2() {
      let pid = this.ruleForm.region2.id
      let obj = this.ruleForm.region2
      this.SearchItem(pid, obj)

      this.AddressCombination["city"] = this.SearchItem(pid, obj)
      console.log(this.AddressCombination)

      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {
          pid
        }
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        console.log(myProvince.data)
        this.ruleForm.region3 = myProvince.data
      }
    },
    region3() {
      let pid = this.ruleForm.region3.id
      let obj = this.ruleForm.region3
      this.SearchItem(pid, obj)

      this.AddressCombination["area"] = this.SearchItem(pid, obj)
      console.log(this.AddressCombination)
    },
    async getInfor() {
      let Province = await this.$http({
        method: "post",
        url: "/api/home/index/linkagearea",
        data: {}
      })
      const myProvince = Province.data
      if (myProvince.State.Code == 200) {
        // console.log(myProvince.data)
        this.ruleForm.region1 = myProvince.data
      }
    },

    handleClose(done) {
      this.$confirm("")
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  },

  mounted() {
    // 三级联动
    this.getInfor()
    this.getAddress()
  }
}
</script>

<style lang="scss" scoped>
.container {
  width: 1200px;
  margin: auto;
  h4 {
    line-height: 50px;
  }
  .flexk {
    width: 1128px;
    height: 47px;
    line-height: 47px;
    background: #f4f4f4;
    border: 1px solid #e2e2e2;
    padding: 0 36px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    p {
      width: 700px;
    }
  }
  .el-dialog {
    .el-dialog__body {
      .dialogk {
        width: 100%;
        position: relative;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        .content-left {
          width: 100%;
          li {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            padding: 10px 0px;
            font-size: 12px;
            .el-radio-group {
              flex: 1;
              padding-right: 10px;
              .el-radio {
                display: inline-block;
                word-break: break-all; // 超出部分换行
                white-space: normal; // 超出部分换行
                .el-radio__label {
                  display: inline-block;
                  width: 80%;
                  overflow: hidden;
                }
              }
            }
          }

          // .el-radio+.el-radio {
          //     margin-left: 0px;
          //     padding-top: 15px;
          // }
        }
      }
      .dialogk2 {
        width: 480px;
        margin: auto;
      }
      .el-button[size="mini"] {
        margin-left: 10px;
      }
    }
  }
}
</style>
